<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se esta autenticado com pelo menos nivel 3
validaPermissao(3);

// Verifica se houve envio do formulario.
if (isset($_POST['submit']))
{
    // Checa se existe entrada
    $result = query_fetch("SELECT id FROM employees WHERE username = '{$_POST['username']}' LIMIT 1");
    if ($result)
    {
       	header( "Location: employee_new.php?msg=Could not add employee: Username {$_POST['username']} already used." );
        die();
    }

	$driverexp = ($_POST['driverexp']? date("'Y-m-d'", strtotime($_POST['driverexp'])) : "NULL");

	// Cria contato
	query_bd("INSERT INTO contacts VALUES " .
	"(NULL, " . ($_POST['name']? "'" . htmlspecialchars($_POST['name']) . "'" : "NULL") .
	", " . ($_POST['number']? "{$_POST['number']}" : "NULL") .
	", " . ($_POST['street']? "'" . htmlspecialchars($_POST['street']) . "'" : "NULL") .
	", " . ($_POST['complement']? "'" . htmlspecialchars($_POST['complement']) . "'" : "NULL") .
	", " . ($_POST['city']? "'" . htmlspecialchars($_POST['city']) . "'" : "NULL") .
	", " . ($_POST['state']? "'" . htmlspecialchars($_POST['state']) . "'" : "NULL") .
	", " . ($_POST['zipcode']? "'" . htmlspecialchars($_POST['zipcode']) . "'" : "NULL") .
	", " . ($_POST['phone']? "'" . htmlspecialchars($_POST['phone']) . "'" : "NULL") .
	", " . ($_POST['cellphone']? "'" . htmlspecialchars($_POST['cellphone']) . "'" : "NULL") .
	", " . ($_POST['email']? "'" . htmlspecialchars($_POST['email']) . "'" : "NULL") . ")");

	$contact_id = mysql_insert_id(); //pega ultimo id inserido

	// Trata figura
	$has_picture = "FALSE";
	if ($_FILES['picture'])
	{
		// Validate the image type. Should be jpeg, jpg, gif or png.
		$allowed = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
		if (! in_array($_FILES['picture']['type'], $allowed))
		{
			$errmsg = '<br>Please ensure the image is a JPEG, GIF or PNG.';
		}
		// Verifica o tamanho do arquivo
		else if (filesize($_FILES['picture']['tmp_name']) > 1024 * 500)
		{
			$errmsg = '<br>Please ensure to send a image smaller than 500kb.';
		}
		else
		{
            $has_picture = "TRUE";
		}
	}

	// Cria employee
	query_bd("INSERT INTO employees VALUES " .
	"(NULL, {$has_picture}, {$contact_id}, '". date("Y-m-d") . "' , NULL, '{$_POST['socialsecurity']}', " .
	"'{$_POST['driverlicense']}', " . ($_POST['driverexp']? "'" . date("Y-m-d", strtotime($_POST['driverexp'])) . "'" : "NULL") .
	", '{$_POST['username']}', '". md5($_POST['pass_one']) . "', {$_POST['permission']}, " .
	($_POST['has_fixed_payrate']? $_POST['payrate'] : "NULL") . ", "  . 
	($_POST['obs']? "'" . mysql_real_escape_string($_POST['obs']) . "'" : "NULL") . ");");

	$employee_id = mysql_insert_id(); //pega ultimo id inserido

    if ($has_picture == "TRUE")
    {
        // Copia imagem para seu destino
        $filename = "portrails/{$employee_id}.jpg";
        copy($_FILES['picture']['tmp_name'], $filename);

        // Cria thumbnail
        // Get new dimensions
        list($width, $height) = getimagesize($filename);
        $crop_factor = (abs($width-48) < abs($height-62)? 
                        $width/48. : $height/62.);
        $crop_width  = 48. * $crop_factor;
        $crop_height = 62. * $crop_factor;

        // Resample
        $image_p = imagecreatetruecolor(48, 62);
        $image = imagecreatefromjpeg($filename);
        imagecopyresampled($image_p, $image, 0, 0, ($width-$crop_width)/2, 
                                                   ($height-$crop_height)/2, 
                                                   48, 62,
                                                   ($width+$crop_width)/2, 
                                                   ($height+$crop_height)/2);
	    // Output
        imagejpeg($image_p, "portrails/{$employee_id}_thumb.jpg", 90);
    }
	header( "Location: employee.php?id={$employee_id}&msg=New employee created." );
	die();
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - New Employee');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
adicionar_js('prototype.js');
adicionar_js('input-format.js');
pagina_head();

// Formulario para criar funcionario
echo "<form id=employee_new class=big_form enctype='multipart/form-data' " .
	"method='POST' action='employee_new.php' onSubmit='return checkForm()'>";
echo "<h1>New Employee</h1><br>";
echo "<label for=name>Name:</label> <input type=TEXT id=name name=name value='' size=40 maxlength=80><br>";
echo "<label for=picture>Picture:</label> <input type=FILE id=picture name=picture><br>";
echo "<hr><h2>Contact</h2><br>";
echo "<label for=number>Number:</label> <input type=TEXT id=number name=number value='' size=8 onChange='format_int(this)'>";
echo " <label for=street>Street:</label> <input type=TEXT id=street name=street value='' size=30 maxlength=50>";
echo " <label for=complement>Complement:</label> <input type=TEXT id=complement name=complement value='' size=10 maxlength=30><br>";
echo "<label for=city>City:</label> <input type=TEXT id=city name=city value='' size=10 maxlength=30>";
echo " <label for=state>State:</label> <input type=TEXT id=state name=state value='' size=8 maxlength=10>";
echo " <label for=zipcode>Zipcode:</label> <input type=TEXT id=zipcode name=zipcode value='' size=6 maxlength=10><br>";
echo "<label for=phone>Phone:</label> <input type=TEXT id=phone name=phone value='' size=12 maxlength=20>";
echo " <label for=cellphone>Cellphone:</label> <input type=TEXT id=cellphone name=cellphone value='' size=12 maxlength=20><br>";
echo "<label for=email>Email:</label> <input type=TEXT id=email name=email value='' size=20 maxlength=30>";
echo "<hr><h2>Work data</h2><br>";
echo "<label for=has_fixed_payrate>Has fixed payrate</label> " .
	"<input type=CHECKBOX name=has_fixed_payrate id=has_fixed_payrate value=1 " .
	"onChange='$(\"payrate_show\").toggle()'><br>";
echo "<div id=payrate_show style='display: none'>";
echo "<label for=payrate>Fixed payrate:</label> " .
	"$<input type=TEXT name=payrate id=payrate size=6 value='0.0' onChange='format_money(this)'><br>";
echo "</div>";
echo "<label for=socialsecurity>Social Security:</label> <input type=TEXT id=socialsecurity name=socialsecurity value='' size=10 maxlength=20><br>";
echo "<label for=driverlicense>Driver license:</label> <input type=TEXT id=driverlicense name=driverlicense value='' size=10 maxlength=20>";
echo " <label for=driverexp>Driver license expiration date:</label> <input id=driverexp type=TEXT name=driverexp value='' size=9>" .
	"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'driverexp', 'chooserSpan1', 2008, 2020, Date.patterns.ShortDatePattern, false);\" alt=''>" .
	"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";;
echo "<hr><h2>Access information</h2><br>";
echo "<label for=username>Username:</label> <input type=TEXT id=username name=username value='' size=15 maxlength=20 onChange='check_username(this.value)'><spam id=username_avaliable></spam><br>";
echo "<label for=pass_one>Password:</label> <input type=PASSWORD id=pass_one name='pass_one' value='' size=15 maxlength=20 onChange='password_check(this.value)'><br>";
echo "<label for=pass_two>Password check:</label> <input type=PASSWORD id=pass_two name='pass_two' value='' size=15 maxlength=20 onChange='password_check(this.value)'><spam id='password_check'></spam><br>";
echo "<label for=permission>Access level:</label> <select id=permission name=permission>";
echo "<option value=1>Valet</option>";
echo "<option value=2>Manager</option>";
echo "<option value=3>Administrator</option>";
if (nivelAutenticado() >= 4)
	echo "<option value=4>Super Administrator</option>";
echo "</select>";
echo "<hr>";
echo "<label for=obs>Observations:</label><br><textarea id=obs name=obs cols=40 rows=5>";
echo "</textarea>";
echo "<hr>";
echo "<input type=SUBMIT name=submit value='Submit'>";
echo "</form>";

?>
<script type="text/javascript" language="JavaScript">

function checkForm()
{
	if ($("name").value.length == 0)
	{
		alert("The Name field must not be empty.");
        $("name").focus();
		return false;
	}
	else if ($("username").value.length == 0)
	{
		alert("The username field must not be empty.");
        $("username").focus();
		return false;
	}
	else if ($("pass_one").value.length == 0)
	{
		alert("The password field must not be empty.");
        $("pass_one").focus();
		return false;
	}
	else if ($("pass_one").value != $("pass_two").value)
	{
		alert("The password check failed.");
        $("pass_two").focus();
		return false;
	}
	else
		return true;
}


function password_check(value)
{   
    if ($("pass_one").value != "" && $("pass_two").value != "")
    {
        if ($("pass_one").value != $("pass_two").value)
        {
            $("password_check").update("password check does not match");
            $("password_check").addClassName("negativo");
            $("password_check").removeClassName("positivo");
        }
        else
        {
            $("password_check").update("ok");
            $("password_check").addClassName("positivo");
            $("password_check").removeClassName("negativo");
        }
    }
    else
        $("password_check").update("");
};

function check_username(value)
{
    if (value != "")
    {
        new Ajax.Request('ajax.php?&option=username&username=' + value, {
            onSuccess: function(response) {
                if (response.responseJSON["response"] == "avaliable")
                {
                    $("username_avaliable").update("username avaliable");
                    $("username_avaliable").addClassName("positivo");
                    $("username_avaliable").removeClassName("negativo");
                }
                else if (response.responseJSON["response"] == "unavaliable")
                {
                    $("username_avaliable").update("username unavaliable");
                    $("username_avaliable").addClassName("negativo");
                    $("username_avaliable").removeClassName("positivo");
                }
                else
                {
                    $("username_avaliable").update("");
                }
            }
        });

    }
    else
    {
        $("username_avaliable").update(""); 
    }
};
</script>

<?php


// Finaliza pagina
pagina_fim();
?>
